// src/auth/ws-jwt.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { WsException } from '@nestjs/websockets';

@Injectable()
export class JwtGuard implements CanActivate {
  constructor(private jwtService: JwtService) {}

  canActivate(context: ExecutionContext): boolean {
    const client = context.switchToWs().getClient();
    const token = client.handshake.auth?.token || client.handshake.query?.token;

    try {
      const payload = this.jwtService.verify(token);
      client.user = payload; // 将用户信息附加到客户端对象
      return true;
    } catch (e) {
      throw new WsException(e);
    }
  }
}
